﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

using Gift.DAL;
using Gift.Model;

namespace WebSite.admin.order
{
    public partial class OrderAdd : BaseAdmin
    {
        readonly OrderAccount theOrderAccount = new OrderAccount();
        readonly DALCardType theCardType = new DALCardType();
        readonly Card theCard = new Card();
        readonly dalCar theDalCar = new dalCar();
        readonly Car theCar = new Car();
        List<tbProfessionAreaType> lstProfessionType = new List<tbProfessionAreaType>();
        readonly DALProfessionAreaType theProfessionAreaType = new DALProfessionAreaType();
        readonly MemberAccount theMemberAccount = new MemberAccount();
        readonly Order theOrder = new Order();

        public string address = "";
        public string carid = "0";
        public string carinfo = "";
        public string cname = "";
        public string email = "";
        public string istrue = "0";
        public string phone = "";
        public string post = "";
        public string score1 = "0";
        public string score2 = "0";
        public string score3 = "0";
        public string shipmsg = "";
        public string tel = "";
        public string totalprice = "0";
        public string totalscore = "0";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddOrder);
                //this.BindNoComplateOrder();
                this.txtSendDate.Text = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
                this.txtNum.Text = "1";
                this.ddlProductList.Items.Add(new ListItem("没有供您选择的商品!"));
            }

        }

        void BindNoComplateOrder()
        {
            DataSet ds;
            ds = theOrderAccount.GetNoComplateAccountList();
            if (ds != null && ds.Tables.Count > 0)
            {
                this.ddlNoComplateOrder.DataTextField = "OrderCode";
                this.ddlNoComplateOrder.DataValueField = "OrderCode";
                this.ddlNoComplateOrder.DataSource = ds.Tables[0].DefaultView;
                this.ddlNoComplateOrder.DataBind();
                this.ddlNoComplateOrder.Items.Insert(0, new ListItem("选择未完成订单编号...", ""));
            }
        }


        void GenerateOrderCode()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["orderCode"]))
            {
                this.lblOrderCode.Text = Request.QueryString["orderCode"];
                this.GetAndBindProfessionArea();
            }
            else
            {
                this.lblOrderCode.Text = theOrderAccount.GenerateOrderCode();
            }
        }
        void GetAndBindProfessionArea()
        {
            this.lblCardDescription.Text = "";
            List<dbCard> lstCard;
            lstCard = theOrderAccount.GetCardAccountList(this.lblOrderCode.Text.Trim());
            int iAmount = 0;
            Hashtable htAmount = new Hashtable();
            Hashtable htCardPassword = new Hashtable();
            this.ddlCards.Items.Clear();
            for (int i = 0; i < lstCard.Count; i++)
            {
                tbProfessionAreaType oProfessionAreaType = new tbProfessionAreaType();
                oProfessionAreaType = theProfessionAreaType.GetModelByCardTypeId(lstCard[i].cardtypeId);
                lstProfessionType.Add(oProfessionAreaType);
                iAmount += int.Parse(lstCard[i].cardprice.ToString());
                this.lblCardDescription.Text += "账户：" + lstCard[i].cardcode
                    + "；  所属专区：" + oProfessionAreaType.Name
                    + "；  金额：" + lstCard[i].cardprice.ToString()
                    + "；<br/>";

                if (htAmount[oProfessionAreaType.Id] == null)
                {
                    htAmount.Add(oProfessionAreaType.Id, lstCard[i].cardprice);
                }
                else
                {
                    htAmount[oProfessionAreaType.Id] = decimal.Parse(htAmount[oProfessionAreaType.Id].ToString()) + lstCard[i].cardprice;
                }
                htCardPassword[lstCard[i].cardcode] = lstCard[i].cardpas;
                this.ddlCards.Items.Add(new ListItem(lstCard[i].cardcode));

            }
            ViewState["amount"] = htAmount;
            ViewState["cardPassword"] = htCardPassword;
            this.lblCardDescription.Text += "                       总额：" + iAmount.ToString();

            this.BindProfessionAreaType();
        }

        void BindProfessionAreaType()
        {
            this.rbtlProfessionList.Items.Clear();
            if (ViewState["amount"] != null)
            {
                Hashtable htAmount = new Hashtable();
                StringBuilder sbLink = new StringBuilder();

                htAmount = (Hashtable)ViewState["amount"];
                string sName = string.Empty;
                foreach (int key in htAmount.Keys)
                {
                    for (int i = 0; i < lstProfessionType.Count; i++)
                    {
                        if (key == lstProfessionType[i].Id)
                        {
                            Decimal dSpendMoney = theCar.GetSpendMoney(this.lblOrderCode.Text, key);

                            sName = lstProfessionType[i].Name
                                             + "(" + (decimal.Parse(htAmount[key].ToString()) - dSpendMoney).ToString()
                                             + "/" + htAmount[key].ToString()
                                             + ")";
                            ListItem item = new ListItem(sName, key.ToString());
                            this.rbtlProfessionList.Items.Add(item);
                            break;
                        }
                    }
                }
            }

        }

        protected void ibtnAdd_Click(object sender, ImageClickEventArgs e)
        {


            System.Diagnostics.Stopwatch s = new System.Diagnostics.Stopwatch();
            s.Start();

            if (string.IsNullOrEmpty(this.lblOrderCode.Text.Trim()))
            {
                base.Response.Write("<script  language='javascript'>alert('请添加新订单!');</script>");
                return;
            }
            dbCard oCard;
            oCard = theCard.GetModel(this.txtCardCode.Text.Trim(), this.txtCardPassword.Text.Trim());
            if (oCard != null)
            {
                if (oCard.states == 0)
                {
                    this.lblCardDescription.Text = "该卡还未激活，请先开卡后才能使用！";
                }
                else if (oCard.states == 2)
                {
                    this.lblCardDescription.Text = "该卡已被使用！";
                }
                else if (oCard.states == 3)
                {
                    this.lblCardDescription.Text = "该卡已失效！";
                }
                else if (oCard.states == 4)
                {
                    this.lblCardDescription.Text = "该卡还未激活,请先开卡后才能使用！";
                }
                else if (oCard.StartTime > DateTime.Now.Date)
                {
                    this.lblCardDescription.Text = "该卡还未生效！";
                }
                else if (oCard.endtime < DateTime.Now.Date)
                {
                    if (oCard.lasttime >= DateTime.Now.Date)
                    {
                        this.lblCardDescription.Text = "该卡的专区有效时间已过,只能到礼品商城兑换商品！";
                    }
                    else
                    {
                        this.lblCardDescription.Text = "该卡已失效！";
                    }
                }
                else if (oCard.states == 1)
                {

                    theOrderAccount.AddCardToCardAccount(this.lblOrderCode.Text.Trim(), oCard.cardid);
                    this.GetAndBindProfessionArea();
                    s.Stop();
                }
            }
            else
            {
                this.lblCardDescription.Text = "卡号或密码不正确！";
            }
        }

        void BindProductList()
        {
            if (!string.IsNullOrEmpty(this.lblOrderCode.Text.Trim()))
            {
                DataTable dtResult = theCar.GetListByOrderCode(this.lblOrderCode.Text.Trim());
                this.GridView1.DataSource = dtResult.DefaultView;
                this.GridView1.DataBind();
            }

        }


        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {


            string sContents = "";// 暂未添加
            if (e.CommandName == "edi")
            {
                if (ViewState["editRowIndex"] != null)
                {
                    int iRowIndex = int.Parse(ViewState["editRowIndex"].ToString());
                    LinkButton lbtEdit = GridView1.Rows[iRowIndex].FindControl("lbtEdit") as LinkButton;
                    LinkButton lbtSave = GridView1.Rows[iRowIndex].FindControl("lbtSave") as LinkButton;
                    LinkButton lbtCancel = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                    TextBox txtNum = GridView1.Rows[iRowIndex].FindControl("txtNum") as TextBox;
                    lbtEdit.Visible = true;
                    lbtSave.Visible = false;
                    lbtCancel.Visible = false;
                    txtNum.Text = ViewState["num"].ToString();
                    txtNum.Enabled = false; ;
                }
                LinkButton lbtEdit2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtEdit") as LinkButton;
                LinkButton lbtSave2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtSave") as LinkButton;
                LinkButton lbtCancel2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                TextBox txtNum2 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("txtNum") as TextBox;
                lbtEdit2.Visible = false;
                lbtSave2.Visible = true;
                lbtCancel2.Visible = true;
                txtNum2.Enabled = true;
                ViewState["editRowIndex"] = e.CommandArgument.ToString();
                ViewState["num"] = txtNum2.Text;
            }
            else if (e.CommandName == "sav")
            {
                LinkButton lbtEdit3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtEdit") as LinkButton;
                LinkButton lbtSave3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtSave") as LinkButton;
                LinkButton lbtCance3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                TextBox txtNum3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("txtNum") as TextBox;
                Label lblPrice3 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lblPrice") as Label;
                Label lblProfessionTypeId = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lblProfessionTypeId") as Label;
                int iProductId = int.Parse(((HyperLink)GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Controls[0]).Text);
                if (txtNum3.Text.Trim() == "0")
                {
                    theCar.Delete(this.lblOrderCode.Text.Trim(), iProductId, sContents);
                }
                else
                {
                    decimal dRemanants = 0;
                    if (ViewState["amount"] != null)
                    {
                        Hashtable htAmount = ViewState["amount"] as Hashtable;
                        decimal dSumPriceByProdId = theCar.GetSumPriceByProdId(int.Parse(((HyperLink)GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Controls[0]).Text), int.Parse(lblProfessionTypeId.Text), sContents);
                        dRemanants = decimal.Parse(htAmount[int.Parse(lblProfessionTypeId.Text)].ToString()) - int.Parse(txtNum3.Text) * decimal.Parse(lblPrice3.Text) - dSumPriceByProdId;

                        if (dRemanants < 0)
                        {
                            Response.Write("<script>alert('余额不够！');</script>");
                            return;
                        }
                        else
                        {
                            tbCar oCar = new tbCar();
                            oCar.OrderCode = this.lblOrderCode.Text.Trim();
                            oCar.ProdNumber = int.Parse(txtNum3.Text);
                            oCar.ProdPrice = decimal.Parse(lblPrice3.Text);
                            oCar.ProductId = iProductId;
                            theCar.Update(oCar);
                        }
                    }
                }

                lbtEdit3.Visible = true;
                lbtSave3.Visible = false;
                lbtCance3.Visible = false;
                txtNum3.Enabled = false; ;
                Response.Write("<script>alert('保存成功！'); </script>");
                this.BindProductList();
                this.GetAndBindProfessionArea();

            }
            else if (e.CommandName == "can")
            {
                LinkButton lbtEdit4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtEdit") as LinkButton;
                LinkButton lbtSave4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtSave") as LinkButton;
                LinkButton lbtCancel4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("lbtCancel") as LinkButton;
                TextBox txtNum4 = GridView1.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("txtNum") as TextBox;
                lbtEdit4.Visible = true;
                lbtSave4.Visible = false;
                lbtCancel4.Visible = false;
                txtNum4.Enabled = false;
            }
            else if (e.CommandName == "del")
            {
                int iProductId = int.Parse(((HyperLink)GridView1.Rows[int.Parse(e.CommandArgument.ToString())].Cells[0].Controls[0]).Text);
                theCar.Delete(this.lblOrderCode.Text.Trim(), iProductId, sContents);
                Response.Write("<script>alert('删除成功！'); </script>");
                this.BindProductList();
                this.GetAndBindProfessionArea();
            }
            if (ViewState["professionAreaSelectID"] != null)
            {
                this.rbtlProfessionList.Items.FindByValue(ViewState["professionAreaSelectID"].ToString()).Selected = true;
            }
        }

        protected void ibtnSubmit_Click(object sender, ImageClickEventArgs e)
        {
            if (this.lblOrderCode.Text == "")
            {
                base.Response.Write("<script  language='javascript'>alert('请选择添加新订单或者选择未完成的订单!');</script>");
                return;
            }
            dbOrder oOrder = new dbOrder();
            dbCar odbCar = new dbCar();
            tbCar oCar = new tbCar();
            decimal dTotalPrice = theCar.GetSpendTotalPrice(this.lblOrderCode.Text.Trim());
            Hashtable htAmount = (Hashtable)ViewState["amount"];
            Hashtable htCardPassword = (Hashtable)ViewState["cardPassword"];
            decimal dCardPrice = 0;
            foreach (int key in htAmount.Keys)
            {
                dCardPrice = dCardPrice + decimal.Parse(htAmount[key].ToString());
            }
            foreach (string key in htCardPassword.Keys)
            {
                dbCard oTmpCard;
                oTmpCard = theCard.GetModel(key, htCardPassword[key].ToString());
                if (oTmpCard == null || oTmpCard.states != 1)
                {
                    base.Response.Write("<script  language='javascript'>alert('此卡已被使用，请重新添加!');</script>");
                    return;
                }
            }

            if (dTotalPrice <= 0)
            {
                base.Response.Write("<script  language='javascript'>alert('您还没有选取要购买商品!');</script>");
                return;
            }
            if (dCardPrice - dTotalPrice > 0)
            {
                base.Response.Write("<script  language='javascript'>alert('您还有余额(" + (dCardPrice - dTotalPrice).ToString() + ")未使用!');</script>");
                return;
            }
            if (dCardPrice - dTotalPrice < 0)
            {
                base.Response.Write("<script  language='javascript'>alert('您的商品价格大于礼品卡金额!');</script>");
                return;
            }

            //  string sOrderId = re.maxid("", "DB_Order", "orderid");
            oOrder.orderid = long.Parse(this.lblOrderCode.Text.Trim());
            oOrder.ordercode = this.lblOrderCode.Text.Trim();
            oOrder.pay = 15;//付款方式为礼品卡
            oOrder.states = 0;
            oOrder.cname = base.AdminUser;
            oOrder.cname1 = this.txtUserName.Text.Trim();
            oOrder.tel1 = this.txtTel.Text.Trim();
            oOrder.phone1 = this.txtPhone.Text.Trim();
            oOrder.post1 = this.txtPost.Text.Trim();
            oOrder.address1 = this.AddressArea1.GetProvenceCity() + this.txtAddress.Text.Trim();
            oOrder.Senddate = this.txtSendDate.Text.Trim() == "" ? DateTime.Now.AddDays(3) : DateTime.Parse(this.txtSendDate.Text.Trim());
            oOrder.ordertime = DateTime.Now;
            oOrder.languages = 1;
            oOrder.cardprice = dCardPrice;
            oOrder.totalprice = dTotalPrice.ToString();
            oOrder.content = this.txtRemark.Text.ToString();
            theOrder.Add(oOrder);

            theDalCar.AddTempToReal(this.lblOrderCode.Text.Trim(), oOrder.orderid);
            theOrderAccount.UpdateComplateAccount(this.lblOrderCode.Text.Trim());
            base.Response.Write("<script  language='javascript'>alert('提交订单成功!请记住订单编号(" + oOrder.ordercode + ")以便查询!');window.location.href='OrderAdd.aspx'</script>");

        }



        protected void ddlNoComplateOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.ddlNoComplateOrder.SelectedItem.Value))
            {
                this.txtCardCode.Text = "";
                this.txtCardPassword.Text = "";
                this.lblCardDescription.Text = "";
                this.rbtlProfessionList.Items.Clear();
                this.txtAddress.Text = "";
                this.txtSendDate.Text = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
                this.txtPhone.Text = "";
                this.txtPost.Text = "";
                this.txtTel.Text = "";
                this.txtUserName.Text = "";
                this.lblOrderCode.Text = this.ddlNoComplateOrder.SelectedItem.Value;
                this.BindProductList();
                this.GetAndBindProfessionArea();
            }
        }

        protected void rbtlProfessionList_SelectedIndexChanged(object sender, EventArgs e)
        {

            // DataTable table = SQLAccess.GreatDs("select proid,proname,proprice1,proprice3,propic2  from DB_Shoppro").Tables[0];
            this.ddlProductList.Items.Clear();
            DataTable table = SQLAccess.GreatDs("select convert(varchar(10),proid) + ', ' + convert(varchar(10),proprice1) as id ,proname + '('+convert(varchar(10),proprice1)+')' as name ,proprice1,propic2  from DB_Shoppro where proisnew2=1 and isnull(proku1,0)>0  and ProfessionAreaTypeId= " + this.rbtlProfessionList.SelectedItem.Value + " order by proname").Tables[0];
            this.ddlProductList.DataTextField = "name";
            this.ddlProductList.DataValueField = "id";
            this.ddlProductList.DataSource = table.DefaultView;
            this.ddlProductList.DataBind();

            if (this.ddlProductList.Items.Count <= 0)
            {
                this.ddlProductList.Items.Add(new ListItem("没有供您选择的商品!", "0"));
            }
        }

        protected void ibtnAddProdut_Click(object sender, ImageClickEventArgs e)
        {
            if (this.rbtlProfessionList.SelectedItem == null)
            {
                base.Response.Write("<script  language='javascript'>alert('请选择专区类别!');</script>");
                return;
            }
            else if (this.ddlProductList.SelectedItem.Value == "0")
            {
                base.Response.Write("<script  language='javascript'>alert('请添加要兑换的商品!');</script>");
                return;
            }
            try
            {
                int.Parse(this.txtNum.Text);
            }
            catch
            {
                base.Response.Write("<script  language='javascript'>alert('数量必须为整数!');</script>");
                return;
            }
            decimal dRemanants = 0;
            //dSpendMoney = theCar.GetSpendMoney(OrderCode, ProfessionTypeId);
            // dRemanants = RemanantsAmount - dSpendMoney;
            Hashtable htAmount = (Hashtable)ViewState["amount"];
            String[] ids = this.ddlProductList.SelectedItem.Value.Split(',');
            decimal dAmount = decimal.Parse(htAmount[int.Parse(this.rbtlProfessionList.SelectedItem.Value)].ToString());
            string sProfessionAreaId = this.rbtlProfessionList.SelectedItem.Value;
            decimal dSpend = decimal.Parse(ids[1]) * int.Parse(this.txtNum.Text);
            dRemanants = dAmount - dSpend;
            ViewState["professionAreaSelectID"] = this.rbtlProfessionList.SelectedItem.Value;

            if (dRemanants >= 0)
            {
                try
                {
                    //添加数据
                    tbCar oCar = new tbCar();
                    oCar.OrderCode = this.lblOrderCode.Text.Trim();
                    oCar.ProdNumber = int.Parse(txtNum.Text);
                    oCar.ProdPrice = decimal.Parse(ids[1]);
                    oCar.ProductId = int.Parse(ids[0]);
                    oCar.UpdateDate = DateTime.Now;
                    theCar.Add(oCar);
                    base.Response.Write("<script  language='javascript'>alert('添加成功！');</script>");
                    this.BindProductList();
                    this.GetAndBindProfessionArea();
                    this.BindProfessionAreaType();
                    this.rbtlProfessionList.Items.FindByValue(sProfessionAreaId).Selected = true;
                }
                catch
                {
                    Response.Redirect("OrderAdd.aspx");
                }
            }
            else
            {
                base.Response.Write("<script  language='javascript'>alert('余额不够，请选择其它商品！');</script>");
            }
        }

        protected void ibtnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (this.ddlCards.SelectedItem != null && !string.IsNullOrEmpty(this.ddlCards.SelectedItem.Value))
            {
                this.theOrderAccount.DeleOrderAccount(this.lblOrderCode.Text.Trim(),int.Parse( this.ddlCards.SelectedItem.Value));
                this.GetAndBindProfessionArea();
            }
        }

        protected void ibtnNewOrder_Click(object sender, ImageClickEventArgs e)
        {
            this.GenerateOrderCode();
            this.BindProductList();
            this.GetAndBindProfessionArea();
            this.BindProfessionAreaType();
        }




    }
}